package casa.depesos.app.com.dlg;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.common.base.utils.WeakHandler;

import java.util.HashMap;
import java.util.List;

import casa.depesos.app.com.R;
import casa.depesos.app.com.adapter.Choose2Adapter;
import casa.depesos.app.com.adapter.ChooseAdapter;
import casa.depesos.app.com.http.data.Province;

public class Choose2Dlg extends ChooseDlg {
    int group, child;
    WeakHandler h = new WeakHandler();

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = super.onCreateView(inflater, container, savedInstanceState);
        binding.sec.setVisibility(View.VISIBLE);
        binding.ok.setEnabled(false);
        binding.ok.setOnClickListener(view1 -> {
            HashMap map = new HashMap();
            map.put("text", binding.level1.getText().toString() + "," + binding.level2.getText().toString());
            map.put("province", group);
            map.put("city", child);
            dismiss(true, map);
        });
        binding.level1.setOnClickListener(view1 -> {
            showParent();
        });
        return view;
    }

    private void showParent() {
        binding.list.scrollToPosition(0);
        ((Choose2Adapter) adapter).resetParent(list, group);
        binding.level1.setText(R.string.choose_province);
        binding.level2.setText(R.string.choose_city);
        binding.level2.setVisibility(View.INVISIBLE);
        binding.ok.setEnabled(false);
    }

    public Choose2Dlg setData(List list, int group, int child, String title) {
        super.setData(list, "", title);
        this.group = group;
        this.child = child;
        return this;
    }

    @Override
    protected ChooseAdapter getAdapter() {
        Choose2Adapter adapter = new Choose2Adapter(list, this);
        if (group >= 0) {
            h.post(() -> {
                onProvinceChange(group, child);
                if (child >= 0) {
                    onCityChange(adapter.getCurrentValue(), child);
                }
            });
        }
        return adapter;
    }

    public void onProvinceChange(int i, int j) {
        group = i;
        binding.list.scrollToPosition(0);
        binding.level2.setVisibility(View.VISIBLE);
        binding.level1.setText(list.get(i).toString());
        adapter.setList(getSecLevel(i), j);
    }

    public void onCityChange(String str, int i) {
        child = i;
        binding.level2.setText(str);
        binding.ok.setEnabled(true);
    }

    private List getSecLevel(int i) {
        return ((Province) list.get(i)).list;
    }
}
